var fs = require('fs');
var lame = require('lame');
var id3 = require('./lib/id3');
var path = require('path');
var DbProvider = require('./server/dbProvider')();
var count = 0;
var mediaItems;
var id3Tags = [];
var errLog;
_ = '\033[0m'; //reset
G = '\033[1;32m';	// hellgrün
R = '\033[31m'; // rot
Y = '\033[1;33m'; // gelb
B = '\033[34m'; // blau
DbProvider.setOptions({
	host: 'localhost',
	port: 27017,
	db: 'colamix'
});
FILEPATH = 'mp3';
DbProvider.connect(function(err, db){
	errLog = fs.createWriteStream('err.log');
	mediaItems = db.getProvider('media');
	console.time('readDir');
	readDir('/');
	console.timeEnd('readDir');
	errLog.end();
});

function readDir(p){
	var relPath = p;
	p = path.join(FILEPATH, p);
	var dir = fs.readdirSync(p);
	var subs = 0;
	var files = 0;
	for(var i in dir){
		var stats = fs.statSync(path.join(p,dir[i]));
		if(stats.isDirectory()){
			subs++
		}else if(stats.isFile()){
			if(path.extname(path.join(p, dir[i])) == ".mp3"){
				count++;
				
				/*
				 * Der Fehler kommt bei mir (vllt. auch wo anders) 
				 * bei mp3s bei denen in Windows in den Eigenschaften 
				 * unter Details keine Länge angegeben is.
				 */
					
				var parser = lame.createParser();
				parser.on('id3v2', function(b){
					id3Tags[i] = id3(b);
					parser.emit('end');
				});

				parser.on('id3v1', function(b){
					//console.log(id3(b));
					parser.emit('end');
				});

				parser.on('end', function(b){
					/*
					 * mediaItem
					 	this.Duration = 0;//!important
						this.Length = 0;//semi important
						var SampleRate = 48000; //muss nich
					  k	this.Url; 
					  k	this.Name; // required
						this.Type;
					  k	this.Meta = {
								title: '', // required
								artist: '' // required
						};
					 */
					var data = {};
					if(id3Tags[i]!=null){
						var tags = id3Tags[i];
						data.Meta = tags;
						if(data.Meta.title){
							data.Name = data.Meta.title;
						}else{
							data.Name = path.basename(dir[i], '.mp3')+' *';
							data.Meta.title = data.Name;
						}
						if(!data.Meta.artist){
							data.Meta.artist = data.Name;
						}
					}else{
						data.Name = path.basename(dir[i], '.mp3')+' *';
						data.Meta = {
								title: data.Name,
								artist: data.Name
						};
					}
					//relative to /mp3
					data.Url = path.join(relPath, dir[i]);
					mediaItems.addItem(data, function(err, saved){
						if(err) throw err;
						files++
						console.log(B,'Song added:', data.Name,_);
					});
				});
				
				var f = fs.readFileSync(path.join(p, dir[i]) );
				try{
					parser.write(f);
				}catch(e){
					console.log(R,"couldn't read file:", path.join(p, dir[i]),_ );
					if(errLog.writable){
						errLog.write(path.join(p, dir[i])+"\n\r");
					};
				}
			}
		}
		
	}
	//ordner in db schreiben

	var state = (subs == 0 && files == 0)?true:false;
	
	var folder = {
		url: relPath,
		empty: state,
		subs: subs,
		files: files
	};
	mediaItems.addDir(folder, function(err, saved){
		if(err) throw err;
		console.log(G,'Folder added:', relPath,_);
	});
	for(var i in dir){
		var stats = fs.statSync(path.join(p,dir[i]));
		if(stats.isDirectory()){
			readDir(path.join(relPath,dir[i]));
		}
	}
};